#pragma once

class CMemDC : public CDC
{
public:

	CMemDC(CDC* pDC) : CDC()
	{
		m_pDC = pDC;
    	pDC->GetClipBox(&m_rect);
		CreateCompatibleDC(pDC);
		m_bitmap.CreateCompatibleBitmap(pDC, m_rect.Width(), m_rect.Height());
		m_pOldBitmap = SelectObject(&m_bitmap);
		SetWindowOrg(m_rect.left, m_rect.top);
	}

	CMemDC(CDC* pDC, CRect rc) : CDC()
	{
        m_pDC = pDC;
		CreateCompatibleDC(pDC);
		m_bitmap.CreateCompatibleBitmap(pDC, rc.Width(), rc.Height());
		m_pOldBitmap = SelectObject(&m_bitmap);
		m_rect = rc;
		SetWindowOrg(m_rect.left, m_rect.top);
	}

	CMemDC( HDC hdc , HBITMAP hBmp ) : CDC() 
	{
		CDC* pDC = CDC::FromHandle( hdc ) ; 
		pDC->GetClipBox(&m_rect);
		CreateCompatibleDC( pDC ) ;
		m_pDC = pDC;
		m_bitmap.FromHandle( hBmp ) ; 
		m_pOldBitmap = SelectObject(&m_bitmap);
		SetWindowOrg(m_rect.left, m_rect.top);
	}


	~CMemDC()
	{
		m_pDC->BitBlt(m_rect.left, m_rect.top, m_rect.Width(), m_rect.Height(),	this, m_rect.left, m_rect.top, SRCCOPY);
		SelectObject(m_pOldBitmap);
		m_bitmap.DeleteObject();
	}

	CMemDC* operator->() {return this;}

	operator CMemDC*() {return this;}

private:
	CBitmap  m_bitmap;
	CBitmap* m_pOldBitmap;
	CDC*     m_pDC;
	CRect    m_rect;
};
